package com.deyuanyun.pic.settings.controller.dto;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserVO;
import com.deyuanyun.pic.settings.domain.prvlg.CustomUser;
import com.deyuanyun.pic.settings.domain.prvlg.Menu;
import com.deyuanyun.pic.settings.service.prvlg.MenuService;
import com.deyuanyun.pic.settings.service.prvlg.UserService;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by xu on 2015/11/25.
 */
public class UserSessionVO extends CustomUser {
    static Logger logger=Logger.getLogger(UserSessionVO.class);

    public UserSessionVO(){}

    private String sessionID;
    private String servletSessionID;
    private Date lastLoginTime;//登录时间
    private ListMultimap<String,Menu> menuListMultimap;//当前登录人所有菜单
    private List<Menu> menuList;
    private String menuString;
    private UserVO userDetailInfo;

    /**设置菜单*/
    public void setMenu(List<Menu> menus){
        this.menuList=menus;
        if (!ObjectUtil.isEmptyAll(menuListMultimap)){
            return;
        }
        if (!ObjectUtil.isEmptyAll(menus)){
            menuListMultimap= ArrayListMultimap.create();
            for (Menu menu : menus){
                if (StringUtils.isBlank(menu.getParentId())||"0".equals(menu.getParentId())){
                    continue;
                }
                menuListMultimap.put(menu.getParentId(),menu);
            }
        }
    }

    /**
     * 获取最顶层大菜单
     * @return
     */
   public List<Menu> getTopMenu(){
       if (menuListMultimap==null){
           MenuService menuService= SpringAppliction.getBean(MenuService.class);
           if ("admin".equals(getUsername())){
               List<Menu> menuList = TempStoreDataSupport.pullDataf("application.menus");
               if (ObjectUtil.isEmptyAll(menuList)){
                   logger.error(">>>出现异常，缓存中没有菜单，重新查询>>");
                   menuList=menuService.querySameLevelMenu("","");
                   TempStoreDataSupport.pushDataf("application.menus",menuList);
               }
               this.setMenu(menuList);
           }else {
               List<Menu> menuList =menuService.queryCurrUserMenu();
               this.setMenu(menuList);
           }
       }
       if (menuListMultimap==null){
           return null;
       }
       return menuListMultimap.get("M0000000000000000000000000000000");
   }

    /**
     * 只包含当前菜单的下一级
     * @param parentId
     * @return
     */
    public List<Menu> getMenuByParentId(String parentId){
        return menuListMultimap.get(parentId);
    }

    /**
     * 包含所有子菜单
     * @param parentId
     * @return
     * @throws Exception
     */
    public List<Menu> getMenusByParentId(String parentId) throws Exception{
        List<Menu> menuList =new ArrayList<Menu>();
        BlockingQueue<String> stringQueu=new ArrayBlockingQueue<String>(100);
        String temId=parentId;
        if (menuListMultimap==null){
            getTopMenu();
        }
        for (;;){
            List<Menu> t_= menuListMultimap.get(temId);
            menuList.addAll(t_);
            for (Menu men:t_){
                stringQueu.offer(men.getId(),2, TimeUnit.SECONDS);
            }
            //temId=stringQueu.poll(1,TimeUnit.SECONDS);
            temId=stringQueu.poll();
            if (stringQueu.isEmpty()&&temId==null){break;}
        }

        Collections.sort(menuList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                Short o11 = o1.getSort();
                o11=o11==null?0:o11;
                Short o22=o2.getSort();
                o22=o22==null?0:o22;
                if (o11 > o22) {
                    return 1;
                } else if (o11 == o22) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });

        return menuList;
    }

    public Menu getMenuById(String id){
        if (menuListMultimap==null){
            getTopMenu();
        }
        List<Menu> menuList =new ArrayList<Menu>(menuListMultimap.values()) ;
        for (Menu m:menuList){
            if (id.equals(m.getId())){
                return m;
            }
        }
        /*Collections2.filter(menuList, new Predicate<Menu>() {
            @Override
            public boolean apply(@Nullable Menu menu) {
                return false;
            }
        });*/
        return null;
    }

    public Menu getMenuByUrl(String pid,String url){
        try {
            List<Menu> menusByParentId=getMenusByParentId(pid);
            for (Menu menu:menusByParentId){
                if (StringUtils.isNotBlank(url) && url.equalsIgnoreCase(menu.getUrl())){
                    return menu;
                }
            }
        } catch (Exception e) {
           logger.error("",e);
            return null;
        }
        return null;
    }


    public ListMultimap<String, Menu> getMenuListMultimap() {
        return menuListMultimap;
    }

    public void setMenuListMultimap(ListMultimap<String, Menu> menuListMultimap) {
        this.menuListMultimap = menuListMultimap;
    }

    public Date getLastLoginTime() {
        return lastLoginTime;
    }

    public void setLastLoginTime(Date lastLoginTime) {
        this.lastLoginTime = lastLoginTime;
    }

    public String getSessionID() {
        return sessionID;
    }

    public void setSessionID(String sessionID) {
        this.sessionID = sessionID;
    }

    public List<Menu> getMenuList() {
        if (menuList==null){
            getTopMenu();
        }
        return menuList;
    }

    public void setMenuList(List<Menu> menuList) {
        this.menuList = menuList;
    }

    public UserVO getUserDetailInfo() {
        if (userDetailInfo==null){
            UserService userService= SpringAppliction.getBean(UserService.class);
            try {
                UserVO userVO=userService.queryUserExpById(getId());
                setUserDetailInfo(userVO);
            } catch (Exception e) {
                logger.error("查询用户信息出错",e);
            }
        }
        return userDetailInfo;
    }

    public String getServletSessionID() {
        return servletSessionID;
    }

    public void setServletSessionID(String servletSessionID) {
        this.servletSessionID = servletSessionID;
    }

    public void setUserDetailInfo(UserVO userDetailInfo) {
        this.userDetailInfo = userDetailInfo;
    }

    public String getMenuString() {
        if (menuList==null){
            getTopMenu();
        }
        return menuString;
    }

    public void setMenuString(String menuString) {
        this.menuString = menuString;
    }
}
